package com.yc.mqtt.handler.message;

import com.yc.mqtt.exception.MqttException;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.*;

import java.net.InetSocketAddress;

public class MqttConnectMessageHandler extends MqttBaseMessageHandler{


    @Override
    public void onMessage(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage) {
        if(! (mqttMessage instanceof MqttConnectMessage) ){
            throw new MqttException("MqttMessage can not convert MqttConnectMessage error");
        }
        MqttConnectMessage mqttConnectMessage = (MqttConnectMessage) mqttMessage;
        MqttFixedHeader mqttFixedHeader = mqttMessage.fixedHeader();

        //连接
        MqttConnectPayload mqttConnectPayload = (MqttConnectPayload) mqttMessage.payload();
        InetSocketAddress socketAddress = (InetSocketAddress)channelHandlerContext.channel().remoteAddress();
        System.out.println(socketAddress.getHostName() + ":" + socketAddress.getPort() + "|username:" + mqttConnectPayload.userName() + " 连接~");

        MqttConnectReturnCode connectReturnCode = MqttConnectReturnCode.CONNECTION_ACCEPTED;
        MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(connectReturnCode, true);
        MqttFixedHeader respMqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, mqttFixedHeader.isDup(), MqttQoS.AT_MOST_ONCE, mqttFixedHeader.isRetain(), 0x02);
        MqttConnAckMessage connAck = new MqttConnAckMessage(respMqttFixedHeader, mqttConnAckVariableHeader);
        channelHandlerContext.channel().writeAndFlush(connAck);// 非清理会话
    }
}
